#ifndef SHA1_HPP
#define SHA1_HPP

#include <string>
#include <cstring>
#if defined(linux)
//openssl库，cmakelist add link -lcrypto
#include <openssl/sha.h>
#include <openssl/crypto.h>
#else
#endif

namespace sh
{
class Sha1
{
public:
#if defined(linux)
    static std::string sha1(const std::string &str)
    {
        SHA_CTX hashCtx;
        unsigned char hashRet[SHA_DIGEST_LENGTH];

        int ret = SHA1_Init(&hashCtx);
        if (ret == 0)
        {
            return "";
        }

        ret = SHA1_Update(&hashCtx, str.c_str(), str.size());
        if (ret == 0)
        {
            return "";
        }

        ret = SHA1_Final(hashRet, &hashCtx);
        if (ret == 0)
        {
            return "";
        }

        OPENSSL_cleanse(&hashCtx, sizeof(hashCtx));

        std::string sha1Text;
        char buf[2] = {'\0'};

        for (int i = 0; i < SHA_DIGEST_LENGTH; ++i)
        {
            memset(buf, '\0', sizeof(buf));
            sprintf(buf, "%02x", hashRet[i]);
            sha1Text += buf;
        }

        return sha1Text;
    }
#else
#endif
};
}

#endif //SHA1_HPP
